/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.felisberto.serialfwder.socket.client;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

/**
 *
 * @author Filipe
 */
public class NettyClient {

    private int port;
    private String hostname;
    private NettyClientHandler handler;
    private Channel session;
    private IDataListener listener;

    public NettyClient(int port,
            String hostname, IDataListener listener) {

        this.hostname = hostname;
        this.port = port;
        this.listener = listener;

    }

    public boolean connect() {
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool()));

        // Configure the pipeline factory.
        handler = new NettyClientHandler(this);
        bootstrap.setPipelineFactory(new NettyClientPipelineFactory(this));

        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(hostname,
                port));

        // Wait until the connection attempt succeeds or fails.
        session = future.awaitUninterruptibly().getChannel();

        if (!future.isSuccess()) {
            System.err.println("connection error: " + future.getCause());
            bootstrap.releaseExternalResources();
            session = null;
            return false;
        }

        return true;
    }
    
    public void relayMessage(String data){
        listener.receiveData(data);
    }
    
    
}
